import nacos
import json
from django.conf import settings
from common.utils.logger import Logger

class NacosConfig:
    _instance = None
    _client = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not self._client:
            # Nacos 客户端配置
            self._client = nacos.NacosClient(
                server_addresses=settings.NACOS_SERVER_ADDRESSES,
                namespace=settings.NACOS_NAMESPACE,
                username=settings.NACOS_USERNAME,
                password=settings.NACOS_PASSWORD
            )
    
    def get_config(self, data_id, group='DEFAULT_GROUP'):
        """
        获取配置
        :param data_id: 配置ID
        :param group: 配置分组
        :return: dict 配置内容
        """
        try:
            content = self._client.get_config(data_id, group)
            return json.loads(content) if content else {}
        except Exception as e:
            Logger.error(f"从Nacos获取配置失败: {str(e)}")
            return {}
    
    def publish_config(self, data_id, group, content):
        """
        发布配置
        :param data_id: 配置ID
        :param group: 配置分组
        :param content: 配置内容
        :return: bool 是否成功
        """
        try:
            return self._client.publish_config(
                data_id,
                group,
                json.dumps(content)
            )
        except Exception as e:
            Logger.error(f"发布配置到Nacos失败: {str(e)}")
            return False
            
    def add_config_watcher(self, data_id, group, callback):
        """
        添加配置监听
        :param data_id: 配置ID
        :param group: 配置分组
        :param callback: 回调函数
        """
        self._client.add_config_watcher(
            data_id,
            group,
            callback
        ) 